package cn.ywang.mybatis.old;

import java.sql.*;

/**
 * 执行器
 *
 * @author BeatificWang
 * @date 2019/9/2 22:36
 */
public class Executor {
	public <T> T query(String sql, Object parameter) {
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		TestTask testTask = null;
		try {
			// 加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8" +
					             "&rewriteBatchedStatements=true";
			// 建立连接
			connection = DriverManager.getConnection(url, "root", "123456");
			// 创建语句集
			ps = connection.prepareStatement(String.format(sql, parameter));
			ps.execute();
			// 结果集
			rs = ps.getResultSet();

			testTask = new TestTask();
			while (rs.next()) {
				;

				testTask.setTaskName(rs.getString("taskName"));
				testTask.setTaskId(rs.getInt("taskId"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (ps != null) {
					ps.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return (T) testTask;
	}
}
